import pinia from '@/store'
import { jpPrinter } from '@/utils/print/tsc';
const permissionsAvailable = pinia.store().useBluetooth
let openBluetoothAdapter = function () {
    return new Promise((resolve, reject) => {
        uni.openBluetoothAdapter({
            success(res) {
                console.log("初始化蓝牙成功");
                resolve(res)
            },
            fail(res) {
                console.log("初始化蓝牙失败" + res);
                reject(res)
            }
        })
    })
};

let getAdapterState = function() {
    return new Promise((resolve, reject) => {
        uni.getBluetoothAdapterState({
            success: (res) => {
                permissionsAvailable.$patch((state)=>{
                    state.bluetoothAvailable = res.available
                    state.bluetoothDiscovering = res.discovering
                })
            },
            fail: (res) => {
                permissionsAvailable.$patch((state)=>{
                    state.bluetoothAvailable = false
                    state.bluetoothDiscovering = false
                })
            }
        })
    })
}

let searchDevice = function() {
    return new Promise((resolve, reject) => {
        console.log("开始搜寻附近的蓝牙外围设备");
        uni.startBluetoothDevicesDiscovery({
            allowDuplicatesKey: true,
            success(res) {
                console.log('startBluetoothDevicesDiscovery:'+res);
                resolve(res)
            },
            fail(res) {
                console.error('startBluetoothDevicesDiscoveryError:'+res);
                reject(res)
            }
        })



    })
};

let connectDevices = function (device) {
    return new Promise((resolve, reject) => {
        console.log("连接蓝牙---------------" + device.deviceId)
        uni.createBLEConnection({
            deviceId: device.deviceId,
            success(res) {
                if (res.errMsg === "createBLEConnection:ok") {
                    console.log("连接蓝牙-[" + device.name + "]--成功");
                    permissionsAvailable.$patch((state)=>{
                        state.bleDevice = device
                    })
                    uni.showToast({
                        title: '连接成功',
                        icon: "none",
                        mask: true,
                        duration: 3000
                    });
                    setTimeout(() => {
                        getBleServices(device.deviceId).then(res => {
                            Object.assign(device, res);
                            const permissionsAvailable = pinia.store().useBluetooth;
                            permissionsAvailable.$patch((state)=>{
                                state.bleDevice = device
                            })
                            resolve(device);
                        }).catch(error => {
                            disconnetDevices();
                            uni.showToast({
                                title: '设备连接失败',
                                icon: "none",
                                mask: true,
                                duration: 1500
                            });
                            reject(error)
                        });
                    }, 3000)
                } else {
                    console.log(res);
                    disconnetDevices();
                    uni.showToast({
                        title: '设备连接失败',
                        icon: "none",
                        mask: true,
                        duration: 1500
                    });
                    reject(res)
                }
                //连接成功 关闭搜索
                stopFindBule();
            },
            fail(res) {
                console.log("连接蓝牙-[" + device.name + "]--失败")
                permissionsAvailable.$patch((state)=>{
                    state.setBleDevice = {}
                })
                reject(res)
            }
        })
    })
};

let disconnetDevices = function() {
    return new Promise((resolve, reject) => {
        let bleDevice = permissionsAvailable.bleDevice
        if (!bleDevice || !bleDevice.deviceId) {
            resolve();
        }
        uni.closeBLEConnection({
            deviceId: bleDevice.deviceId,
            success(res) {
                console.log("关闭连接设备" + bleDevice.deviceId + "成功")
                permissionsAvailable.$patch((state)=>{
                    state.bleDevice = {}
                })
                resolve();
            },
            fail(error) {
                if (error.errCode === 10006) {
                    permissionsAvailable.$patch((state)=>{
                        state.bleDevice = {}
                    })
                    resolve()
                }
                permissionsAvailable.$patch((state)=>{
                    state.bleDevice = {}
                })
                reject(error);
            }
        })
    })
}

let getBleServices = function (deviceId) {
    return new Promise((resolve, reject) => {
        console.log("获取蓝牙设备所有服务(service)。---------------")
        uni.getBLEDeviceServices({
            // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
            deviceId: deviceId,
            success(res) {
                console.log(res);
                for (var s = 0; s < res.services.length; s++) {
                    let serviceId = res.services[s].uuid;
                    uni.getBLEDeviceCharacteristics({
                        // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
                        deviceId: deviceId,
                        // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
                        serviceId: serviceId,
                        success(res) {
                            for (let c = 0; c < res.characteristics.length; c++) {
                                if (res.characteristics[c].properties.write === true) {
                                    let uuid = res.characteristics[c].uuid;
                                    console.log('找到可写入的特征值:deviceId = [' + deviceId + ']  serviceId = [' + serviceId + '] characteristics=[' +
                                        uuid);
                                    resolve({
                                        serviceId: serviceId,
                                        characteristicId: uuid
                                    });
                                    break;
                                }
                            }
                        },
                        fail(error) {
                            reject(error);
                        }
                    })
                }
            },
            fail(res) {
                console.log(res);
                reject(res)
            },
        })
    })
};

let stopFindBule = function () {
    return new Promise((resolve, reject) => {
        console.log("停止搜寻附近的蓝牙外围设备---------------");
        uni.stopBluetoothDevicesDiscovery({
            success(res) {
                resolve(res)
            }
        })
    })
};

let closeBluetoothAdapter = function () {
    return new Promise((resolve, reject) => {
        uni.closeBluetoothAdapter({
            success(res) {
                console.log(res)
            }
        })
    })
};

let senBlData = function (uint8Array) {
    return new Promise((resolve, reject) => {
        console.log("调用打印方法");
        let bleDevice = permissionsAvailable.bleDevice
        if (!bleDevice.deviceId) {
            console.log("未连接打印机");
            reject("未连接打印机");
        }
        var uint8Buf = Array.from(uint8Array);

        var sendloop = split_array(uint8Buf, 20);
        // console.log(sendloop.length)

        var i = 0;
        realWriteData(sendloop, i);
        uni.showToast({
            title: '打印数据已发送',
            icon: "none",
            mask: true,
            duration: 1500,
            success(){
                setTimeout(() => {
                    resolve()
                }, 1500)
            }
        });
    })

};
let realWriteData = function(sendloop, i) {
    let device = permissionsAvailable.bleDevice
    var data = sendloop[i]
    if(typeof(data) == "undefined"){
        return
    }
    console.log("第【" + i + "】次写数据"+data)
    var buffer = new ArrayBuffer(data.length)
    var dataView = new DataView(buffer)
    for (var j = 0; j < data.length; j++) {
        dataView.setUint8(j, data[j]);
    }
    uni.writeBLECharacteristicValue({
        deviceId: device.deviceId,
        serviceId: device.serviceId,
        characteristicId: device.characteristicId,
        value: buffer,
        success(res) {
            realWriteData(sendloop, i + 1);
            /* setTimeout(() => {
                realWriteData(sendloop, i + 1);
            }, 10); */
        }, fail(error) {
            uni.showToast({
                title: '打印失败，请重试',
                icon: "none",
                mask: true,
                duration: 1500,
                success() {
                    setTimeout(() => {
                    }, 1500)
                }
            });
        }
    })
}

function split_array(datas,size){
    var result = {};
    var j = 0
    for (var i = 0; i < datas.length; i += size) {
        result[j] = datas.slice(i, i + size)
        j++
    }
    console.log(result)
    return result
}

//80*60样式
function senBleLabel() {
    return new Promise((resolve, reject) => {
        //标签模式f
        var printData = store.state.printDetailData;
        var command = jpPrinter.createNew();
        printData.certificateNoList.forEach(no => {
            // console.log(command)
            command.setSize(80, 60);
            command.setCls();
            command.setText(16 * 8, 1.5 * 8, "TSS24.BF2", 2, 2, "食用农产品合格证");
            command.setText(35 * 8, 8 * 8, "TSS24.BF2", 1, 1, "编号：" + no.fullNumber);
            command.setText(3.5 * 8, 11 * 8, "TSS24.BF2", 1, 1, "食用农产品名称：" + printData.productName);
            command.setText(3.5 * 8, 15 * 8, "TSS24.BF2", 1, 1, "数量（重量）：" + printData.productNum + printData.productUnitName);
            command.setText(3.5 * 8, 19 * 8, "TSS24.BF2", 1, 1, "生产者：" + printData.entName);
            command.setText(3.5 * 8, 23 * 8, "TSS24.BF2", 1, 1, "联系方式：" + printData.entContactsPhone);
            command.setText(3.5 * 8, 27 * 8, "TSS24.BF2", 1,1 , "开具日期："+ printData.createDate.substring(0,10));
            command.setText(3.5 * 8, 31 * 8, "TSS24.BF2", 1, 1, "产地：" + printData.productDetail);

            command.setText(3.5 * 8, 37 * 8, "TSS24.BF2", 1, 1, "我承诺对产品质量安全以及合格证真实性负责");
            command.setText(3.5 * 8, 41 * 8, "TSS24.BF2", 1, 1, "·不使用禁限用农药兽药");
            command.setText(3.5 * 8, 45 * 8, "TSS24.BF2", 1, 1, "·不使用非法添加物");
            command.setText(3.5 * 8, 49 * 8, "TSS24.BF2", 1, 1, "·遵守农药安全间隔期、兽药休药期规定");
            command.setText(3.5 * 8, 53 * 8, "TSS24.BF2", 1, 1, "·销售的食用农产品符合农药兽药残留食品安全国家标准");


            command.setText(59 * 8, 27 * 8, "TSS24.BF2", 1, 1, "扫描二维码");
            command.setText(58 * 8, 30.5 * 8, "TSS24.BF2", 1, 1, "查看更多信息");

            command.setQR(59 * 8, 12.5 * 8, "L", 3, "A", viewCertificateUrl + "/a/bas/certificate/viewScanCertificateNo?id=" + no.id);
            command.setPagePrint(1);
        })


        senBlData(command.getData()).then(res => {
            resolve()
        });
    })

}

//60*40样式
function senBle60Label() {
    return new Promise((resolve, reject) => {
        //标签模式f
        let printData = permissionsAvailable.printData
        var command = jpPrinter.createNew();
        console.log('command',command)
        printData.forEach(item => {
            // console.log(command)
            command.setSize(60, 40);
            command.setCls();
            command.setDirection(1);

            command.setBox(8 * 6,3*6,80 * 6,11 * 6,2)
            command.setText(32 * 6, 5*6, "TSS24.BF2", 1, 1, "食品留样标签");

            command.setBox(8 * 6,11*6,26 * 6,19 * 6,2)
            command.setText(13 * 6, 13*6, "TSS24.BF2", 1, 1, "组织");
            command.setBox(26 * 6,11*6,80 * 6,19 * 6,2)
            command.setText(27 * 6, 13*6, "TSS24.BF2", 1, 1, item.orgName);


            command.setBox(8 * 6,19*6,26 * 6,27 * 6,2)
            command.setText(11 * 6, 21*6, "TSS24.BF2", 1, 1, "食品名");
            command.setBox(26 * 6,19*6,80 * 6,27 * 6,2)
            command.setText(27 * 6, 21*6, "TSS24.BF2", 1, 1, item.recipeMenuItemDetail);

            command.setBox(8 * 6,27*6,26 * 6,35 * 6,2)
            command.setText(13 * 6, 29*6, "TSS24.BF2", 1, 1, "餐次");
            command.setBox(26 * 6,27*6,44 * 6,35 * 6,2)
            command.setText(27 * 6, 29*6, "TSS24.BF2", 1, 1, item.mealTimesName);
            command.setBox(44 * 6,27*6,62 * 6,35 * 6,2)
            command.setText(49 * 6, 29*6, "TSS24.BF2", 1, 1, "重量");
            command.setBox(62 * 6,27*6,80 * 6,35 * 6,2)
            command.setText(63 * 6, 29*6, "TSS24.BF2", 1, 1,  item.reservedAmount+'克');

            command.setBox(8 * 6,35*6,26 * 6,43 * 6,2)
            command.setText(9 * 6, 37*6, "TSS24.BF2", 1, 1, "留样时间");
            command.setBox(26 * 6,35*6,80 * 6,43 * 6,2)
            command.setText(27 * 6, 37*6, "TSS24.BF2", 1, 1, item.reservedDate);

            command.setBox(8 * 6,43*6,26 * 6,51 * 6,2)
            command.setText(9 * 6, 45*6, "TSS24.BF2", 1, 1, "留样时长");
            command.setBox(26 * 6,43*6,44 * 6,51 * 6,2)
            command.setText(27 * 6, 45*6, "TSS24.BF2", 1, 1, item.disposeHours+'小时');
            command.setBox(44 * 6,43*6,62 * 6,51 * 6,2)
            command.setText(47 * 6, 45*6, "TSS24.BF2", 1, 1, "留样人");
            command.setBox(62 * 6,43*6,80 * 6,51 * 6,2)
            command.setText(63 * 6, 45*6, "TSS24.BF2", 1, 1,  item.updateByName ? item.updateByName.length>4 ? item.updateByName.substring(0,4) : item.updateByName : '');
            command.setPagePrint(1);
        })


        senBlData(command.getData()).then(res => {
            resolve()
        });
    })

}

//选择打印样式
function chooseBlueTypeLabel(type) {
    return new Promise((resolve, reject) => {
        //60*40样式
        if(1==type){
            senBle60Label();
        }
        //80*60样式
        else if(2==type){
            senBleLabel();
        }
        //默认打印
        else{
            senBle80Label();
        }
        resolve()
    })


}

export default {
    openBluetoothAdapter,
    searchDevice,
    connectDevices,
    getBleServices,
    stopFindBule,
    disconnetDevices,
    closeBluetoothAdapter,
    getAdapterState,
    chooseBlueTypeLabel,
}
